package com.example.demo.jdk.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象克隆工具
 *
 * @author: htc
 * @date: Created in 15:36 2019/4/2.
 */
public class CloneUtils {
    /**
     * 浅克隆
     *
     * @param source
     * @param targetClazz
     * @param <T>
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> T shallowClone(Object source, Class<T> targetClazz) throws IllegalAccessException, InstantiationException {
        T target = targetClazz.newInstance();
        BeanCopierUtils.copyProperties(source, target);
        return target;
    }

    /**
     * 浅克隆集合
     *
     * @param sourceList
     * @param targetClazz
     * @param <T>
     * @return
     */
    public static <T> List<T> shallowCloneList(List<? extends Object> sourceList, Class<T> targetClazz) {
        List<T> targetList = new ArrayList<T>(sourceList.size());
        sourceList.forEach(e -> {
            try {
                targetList.add(shallowClone(e, targetClazz));
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            }
        });
        return targetList;
    }
}
